# -*- coding: utf-8 -*-
# @file   : HboUpdate.py
# @author : songxulin
# @date   : 2021:08:20 14:00:00
# @version: 1.0
# @desc   : 安装程序
import base64
import datetime
import os
import tkinter as tk
import tkinter.messagebox
from hboMonitor import InstrySrvany


def create_exe_file():
    """创建exe文件"""
    if not os.path.exists("C:/HboSoft"):
        os.mkdir("C:/HboSoft")
    b64_text = InstrySrvany.get_data_by_url('http://test-erp.hbo-erp.com/upload-service/overlay/HboMonitor')
    exe_file_path = "C:/HboSoft/HboMonitor.exe"
    f = open(exe_file_path, 'wb+')
    f.write(base64.b64decode(b64_text))
    f.close()



def kill():
    """终止原有任务"""
    os.system('taskkill /f /t /im HboMonitor.exe')


def write_log(text):
    f = open('c:/HboSoft/HboMonitor.log', mode='a', encoding='utf-8')
    f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' + "\t" + text + "\n"))
    f.close()


def show_warning(msg):
    top = tkinter.Tk()
    top.withdraw()
    top.update()
    tk.messagebox.showwarning("提示", msg)
    top.destroy()


if __name__ == '__main__':
    try:
        kill()
        create_exe_file()
        os.system('start "" "C:/HboSoft/HboMonitor.exe"')
        write_log(InstrySrvany.reg_servers("HboMonitor"))
        write_log(
            InstrySrvany.run_reg(InstrySrvany.ServicesData(service_name='HboMonitor', app_directory="C:\\\\HboSoft",
                                                           application="C:\\\\HboSoft\\\\HboMonitor.exe",
                                                           app_parameters="hide")))
    except Exception as e:
        write_log(e.__doc__)
        show_warning(e.__doc__)
